package com.applet.applet_shangcheng.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.applet.applet_shangcheng.dao.ImagesMapper;
import com.applet.applet_shangcheng.entity.IntegralGoods;
import com.applet.applet_shangcheng.entity.IntegralMalls;
import com.applet.applet_shangcheng.service.IntegralService;
import com.applet.applet_shangcheng.service.OrderService;
import com.applet.applet_shangcheng.utlis.PageResult;
import com.applet.applet_shangcheng.utlis.QueryPageBean;
import com.applet.applet_shangcheng.utlis.Result;
import com.applet.applet_shangcheng.utlis.StatusCode;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/integral")
@CrossOrigin
@Api(value="积分商城管理",tags={"积分商城管理"})
public class IntegralController {
    @Autowired
    private IntegralService integralService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private ImagesMapper imagesMapper;
    //小程序
    @ApiOperation(value="WX_获取积分商场分类")
    @GetMapping("/WXfindAllS")
    public Result findAllS() {
        List<IntegralGoods> inList = integralService.findAllS();
        return new Result(true, StatusCode.OK, "积分商城分类查询成功", inList);
    }
    @ApiOperation(value="查询所有积分商品")
    @GetMapping("/findAll")
    public Result findAll() {
        List<IntegralMalls> mallsList = integralService.findAll();
        return new Result(true, StatusCode.OK, "积分商城分类查询成功", mallsList);
    }

    @ApiOperation(value="_积分折线图")
    @GetMapping("/getOrderTodayS/{datetime}/{datetime2}")
    public Result getOrderTodayS(@PathVariable("datetime") String datetime,
                                 @PathVariable("datetime2") String datetime2) {
        String years = datetime.substring(0, 4);//年
        String monthd = datetime.substring(datetime.indexOf('-') + 1);
        String monthds1 = monthd.substring(0, 2);//月
        String substring = monthds1.substring(1);
        if (substring.equals("-")) {
            monthds1 = monthds1.substring(0, 1);
        }
        String dates = datetime.substring(datetime.lastIndexOf("-") + 1);//日
        String years2 = datetime2.substring(0, 4);//年
        String monthd2 = datetime2.substring(datetime2.indexOf('-') + 1);
        String monthds = monthd2.substring(0, 2);//月
        String substring2 = monthds.substring(1);
        if (substring2.equals("-")) {
            monthds = monthds.substring(0, 1);
        }
        String dates2 = datetime2.substring(datetime2.lastIndexOf("-") + 1);//日
        System.out.println(years + monthds1 + dates);
        System.out.println(years2 + monthds + dates2);
        Calendar begin = Calendar.getInstance();
        begin.set(Calendar.YEAR, Integer.parseInt(years));
        begin.set(Calendar.MONTH, Integer.parseInt(monthds1) - 1);
        begin.set(Calendar.DATE, Integer.parseInt(dates));
        Calendar end = Calendar.getInstance();
        end.set(Calendar.YEAR, Integer.parseInt(years2));
        end.set(Calendar.MONTH, Integer.parseInt(monthds) - 1);
        end.set(Calendar.DATE, Integer.parseInt(dates2));
        List<String> months = new ArrayList<>();
        while (!end.before(begin)) {
            months.add(new SimpleDateFormat("yyyy-MM-dd").format(begin.getTime()));
            begin.add(Calendar.DATE, 1);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("months", months);
        List<Integer> hasPay = new ArrayList<>();
        for (String month : months) {
            hasPay.add(integralService.getHasPay(month));
        }
//        List<String>hasPay = orderService.getHasPay();
        map.put("hasPay", hasPay);
        List<Integer> notPay = new ArrayList<>();
        for (String month : months) {
            notPay.add(integralService.getNotPay(month));
        }
        map.put("notPay", notPay);
        if (map == null) {
            return new Result(false, StatusCode.ERROR, "失败");
        }
        return new Result(true, StatusCode.OK, "成功", map);
    }
    @ApiOperation(value="_积分商场饼图")
    @GetMapping("/getOrderTodayS/{datetime}")
    public Result getOrderTodayS(@PathVariable("datetime") String datetime) {
        Map<String, Object> map = new HashMap<String, Object>();
        String years = datetime.substring(0, 4);//年
        String monthd = datetime.substring(datetime.indexOf('-') + 1);
        String monthds1 = monthd.substring(0, 2);//月
        String substring = monthds1.substring(1);
        if (substring.equals("-")) {
            monthds1 = monthds1.substring(0, 1);
        }
        if (!substring.equals("0")) {
            monthds1 = "0" + monthds1;
        }
        String dates = datetime.substring(datetime.lastIndexOf("-") + 1);//日
        String datesS = dates.substring(0, 1);//月
        if (!datesS.equals("0")&&dates.length()<2) {
            dates = "0" + dates;
        }
        String datetimeD = years +"-"+ monthds1+"-" + dates;
        System.out.println(datetimeD);
        List<Map<String, Object>> list = orderService.getHasIGoodsNameList(datetimeD);
        map.put("goodsNameList", list);
        List<String> setmealNames = new ArrayList<String>();
        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);
        if (list.size() == 0) {
            return new Result(false, StatusCode.ERROR, datetime+"今日没有新的订单!", map);
        }
        if (map == null) {
            return new Result(false, StatusCode.ERROR, datetime+"今日没有新的订单!");
        }
        return new Result(true, StatusCode.OK, "查询成功", map);
    }

    @ApiOperation(value="_积分饼图")
    @GetMapping("/getOrderToday")
    public Result getOrderToday() {
        Map<String, Object> map = new HashMap<String, Object>();
        Calendar calendar = Calendar.getInstance();
        String time = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
        List<Map<String, Object>> list = orderService.getHasIGoodsNameList(time);
        map.put("goodsNameList", list);
        List<String> setmealNames = new ArrayList<String>();
        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);
        if (list.size() == 0) {
            return new Result(false, StatusCode.ERROR, "今日没有新的订单!", map);
        }
        if (map == null) {
            return new Result(false, StatusCode.ERROR, "今日没有新的订单!");
        }
        return new Result(true, StatusCode.OK, "查询成功", map);
    }
    @ApiOperation(value="_积分饼图")
    @GetMapping("/getOrderTotalNumber")
    public Result getOrderTotalNumber() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> months = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        // 根据当前时间-12，算出12个月之前的时间
        calendar.add(Calendar.DATE, -7);
        for (int i = 1; i <= 7; i++) {
            calendar.add(Calendar.DATE, 1); //12个月之前的时间+1，得到2018-10
            months.add(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
        }
        map.put("months", months);
        List<Integer> hasPay = new ArrayList<>();
        for (String month : months) {
            hasPay.add(integralService.getHasPay(month));
        }
//        List<String>hasPay = orderService.getHasPay();
        map.put("hasPay", hasPay);
        List<Integer> notPay = new ArrayList<>();
        for (String month : months) {
            notPay.add(integralService.getNotPay(month));
        }
        map.put("notPay", notPay);
        if (map == null) {
            return new Result(false, StatusCode.ERROR, "失败");
        }
        return new Result(true, StatusCode.OK, "成功", map);
    }

    @ApiOperation(value="_分页查询积分商场订单")
    //查询所有有效状态
    @PostMapping("/findAll1")
    public PageResult findAll1(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = integralService.findAll1(queryPageBean.getQueryString(), queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        return pageResult;
    }
    @ApiOperation(value="_分页查询积分商品分类")
    @PostMapping("/calssFindAll")
    public PageResult calssFindAll(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = integralService.calssFindAll(queryPageBean.getQueryString(), queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        return pageResult;
    }
    @ApiOperation(value="_添加分类")
    @PostMapping("/insertGoodsClass")
    public Result insertGoodsClass(@RequestBody  IntegralMalls integralMalls) {
        String sortId = integralMalls.getSortId();
        IntegralMalls integralMalls1s =   integralService.findBySortId(Integer.parseInt(sortId));
        if (integralMalls1s!=null){
            return new Result(false, StatusCode.ERROR, "分类id重复");
        }
        int result = integralService.insertGoodsClass(integralMalls);
        if (result > 0) {
            return new Result(true, StatusCode.OK, "添加成功");
        }
        return new Result(false, StatusCode.ERROR, "添加失败");
    }

    @ApiOperation(value="_根据sortId查询分类详情")
    @GetMapping("/selectGoods/{sortId}")
    public Result selectGoods(@PathVariable("sortId") String sortId) {
        Map map = integralService.selectGoods(sortId);
        return new Result(true, StatusCode.OK, "积分商城'分类详情'查询成功", map);
    }

    @ApiOperation(value="_根据id查询积分商品详情")
    @GetMapping("/findById/{id}")
    public Result findById(@PathVariable("id") int id) {
        IntegralGoods integralGoods = integralService.findById(id);
        if (integralGoods != null) {
            return new Result(true, StatusCode.OK, "商品查询成功", integralGoods);
        }
        return new Result(false, StatusCode.ERROR, "商品查询不存在");
    }
    @ApiOperation(value="_根据id查询积分商品详情")
    @GetMapping("/findIntegralId/{id}")
    public Result findIntegralId(@PathVariable("id") int id) {
        IntegralGoods integralGoods = integralService.findByIdAll(id);
        if (integralGoods != null) {
            return new Result(true, StatusCode.OK, "商品查询成功", integralGoods);
        }
        return new Result(false, StatusCode.ERROR, "商品查询失败");
    }
    @ApiOperation(value="_添加积分商品详情")
    @PostMapping("/insertGoods")
    public Result insertIntegralGoods(@RequestBody IntegralGoods integralGoods) throws JsonProcessingException {
        String goodsId = String.valueOf(integralGoods.getGoodsId());
        if (goodsId.length()>11) {
            return new Result(false, StatusCode.ERROR, "商品编号不能超过11位!");
        }
        if (integralGoods.getGoodsId() == 0) {
            return new Result(false, StatusCode.ERROR, "商品编号不能为空!");
        }
        if (integralGoods.getGoodsName() == null) {
            return new Result(false, StatusCode.ERROR, "商品名称不能为空!");
        }
        if (integralGoods.getImage()!=null){
            imagesMapper.InsertImageStatus(integralGoods.getImage(),"1");
        }
        if (integralGoods.getImagess()!=null) {
            List<String> imagess = integralGoods.getImagess();
            for (String s : imagess) {
                imagesMapper.InsertImageStatus(s,"1");
            }
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(imagess);
            System.out.println(s);
            integralGoods.setImages(s);
        }
        integralGoods.setCreateTime(new Date());
        int result = integralService.insertIntegralGoods(integralGoods);
        if (result > 0) {
            return new Result(true, StatusCode.OK, "商品添加成功");
        }
        return new Result(false, StatusCode.ERROR, "商品添加失败,商品名称或id重复");
    }
    @ApiOperation(value="_修改积分商品详情")
    @PostMapping("/updateGoods")
    public Result updateGoods(@RequestBody IntegralGoods integralGoods) {
        int result = integralService.updateGoods(integralGoods);
        if (result > 0) {
            return new Result(true, StatusCode.OK, "修改成功");
        }
        return new Result(false, StatusCode.ERROR, "修改失败");
    }

    @ApiOperation(value="_根据id删除积分商品详情")
    @GetMapping("/deleteGoods/{id}")
    public Result deleteGoods(@PathVariable("id") int id) {
        IntegralGoods goods = integralService.findById(id);
        if (goods.getImage()!=null){
            imagesMapper.updateImageStatus(goods.getImage());
        }
        String images = goods.getImages();
        if (!images.equalsIgnoreCase("null")&&images.length()>0) {
            JSONArray objects = JSON.parseArray(images);
            for (Object object : objects) {
                imagesMapper.updateImageStatus(object.toString());
            }
        }
        int result = integralService.deleteGoods(id);
        if (result > 0) {
            return new Result(true, StatusCode.OK, "删除成功");
        }
        return new Result(false, StatusCode.ERROR, "删除失败");
    }
    @ApiOperation(value="_根据id删除积分商品分类")
    @GetMapping("/deleteGoodsclass/{id}")
    public Result deleteGoodsclass(@PathVariable("id") int id) {
        int result = integralService.deleteGoodsclass(id);
        if (result > 0) {
            return new Result(true, StatusCode.OK, "删除成功");
        }
        return new Result(false, StatusCode.ERROR, "删除失败,请先删除商品列关联商品!");
    }
}
